// Author: wsfuyibing <682805@qq.com>
// Date: 2025-07-01

package buy

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/http/logics/detail"
	"server/app/http/models"
	"server/app/lib"
	"server/app/lib/authorizer"
	"server/app/lib/order/operations"
)

// Logic
// 商品下单.
type Logic struct {
	detail.Logic

	auth   *authorizer.Authentication
	entity *operations.GoodsEntity

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.auth = authorizer.New().Get(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)

	// 1. 下单过程.
	if err = db.Transaction(ctx,
		o.RunPrepay,
		o.RunCreate,
	); err != nil {
		return res.WithError(err)
	}

	// 2. 下单完成.
	return res.With(o.response)
}

// RunCreate
// 执行下单.
func (o *Logic) RunCreate(ctx context.Context, sess *db.Session) (err error) {
	var order *models.Order
	if order, err = lib.Order.CreateOnGoods(ctx, sess, o.entity, o.response.Prepay); err == nil {
		o.response.WithOrder(order)
	}
	return
}

// RunPrepay
// 执行试算.
func (o *Logic) RunPrepay(ctx context.Context, sess *db.Session) (err error) {
	// 1. 构建入参.
	o.entity = lib.Order.NewGoodsEntity()
	o.entity.UseUserBalance = o.request.UseUserBalance

	// 2. 买卖双方.
	o.entity.ArcadeId = o.request.ArcadeId
	o.entity.UserId = o.auth.UserId

	// 3. 买入商品.
	o.entity.Carts = o.request.Carts

	// 4. 支付元素.
	//    a. 会员抵扣
	//    b. 余额抵扣
	//    c. 优惠券抵扣
	o.entity.CouponId = o.request.CouponId

	// 5. 处理试算.
	o.response.Prepay, err = lib.Order.PrepayOnGoods(ctx, sess, o.entity)
	return
}
